package com.example.simplesvc;

import org.apache.commons.io.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;

@Service
public class ExamplePromleService {


    private static Logger log = LoggerFactory.getLogger(ExamplePromleService.class);
    public String startAUnstopThread() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
             for(;;) {
                 log.info("{} processing biz at {}",Thread.currentThread().getName(), System.currentTimeMillis());
                 try {
                     ThreadUtils.sleep(Duration.of(10, ChronoUnit.SECONDS));
                 }catch (Exception e) {
                     //
                 }

                 //检查服务器状态，发现正处于关闭状态 则推出线程执行不再循环
                 if(ServerStateHolder.getInstance().isServerStopping()) {
                     return;
                 }

             }
            }
        };

        Thread thread = new Thread(runnable,"my_unstop_thread-"+System.currentTimeMillis());

        thread.setDaemon(false);
        thread.start();

        return "success";
    }

    public void createInstanceOutOfSpringContext() {

        MyOutOfSpringService svc = new MyOutOfSpringService();

        // 通过executor 对象 执行一个永不停止的任务，这样executor的工作线程就不会退出，如果不显式关闭executor，那么tomcat也不会退出
        svc.runWithExecutor(new Runnable() {
            @Override
            public void run() {
                for(;;) {
                    log.info("executor thread {}  processing  biz at {}",Thread.currentThread().getName(), System.currentTimeMillis());
                    try {
                        Thread.sleep(5000);
                    }catch (Exception e) {
                        //
                    }

                    if(ServerStateHolder.getInstance().isServerStopping()) {
                        return;
                    }
                }
            }
        });

        //启动一个周期定时任务 打印日志 永不停止，这样timer的工作线程就不会退出，如果不显式关闭timer，那么tomcat也不会退出
        svc.runWithTimer(new Runnable() {
            @Override
            public void run() {
                log.info("timer thread {}  processing biz  at {}",Thread.currentThread().getName(), System.currentTimeMillis());
            }
        });

    }
}
